package com.yicheng.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import netscape.javascript.JSObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

//每日文案
public class EnglishWorlds {
    public String[] englishWorlds(){
        //java环境中文传值时，需特别注意字符编码问题
        //https://www.tianapi.com/apiview/194   天性数据每日文案的网址
        String httpUrl = "http://api.tianapi.com/pyqwenan/index";//请求网址
        String httpArg = "key=4afea454c78705dab1a07e2730120f26";//请求参数 key
        String jsonResult = request(httpUrl, httpArg);
//        System.out.println(jsonResult);
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        JSONArray jsonArray = jsonObject.getJSONArray("newslist");
        String[] strings = new String[2];
        strings[0] = jsonArray.getJSONObject(0).get("content").toString();
        strings[1] = jsonArray.getJSONObject(0).get("source").toString();
        return strings;
    }


    /**
     * @param httpUrl  请求接口
     * @param httpArg  参数
     * @return 返回结果
     */

    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
